package com.lsk.mps.backend.redis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

@Component
public class RedisDao {
    private JedisPool pool;

    @Autowired
    public RedisDao(RedisProperties properties) {
        this.pool = new JedisPool(new GenericObjectPoolConfig(),
                    properties.getHost(),
                    properties.getPort(),
                    5000,
                    properties.getPassword(),
                    properties.getDb()
                );
    }

    @Bean
    public JedisPool jedisPool() {
        return this.pool;
    }

    public void set(String key, String value, int expire) {
        try (Jedis jedis = this.pool.getResource()) {
            jedis.set(key, value);
            jedis.expire(key, expire);
        }
    }

    public void set(String key, String value) {
        try (Jedis jedis = this.pool.getResource()) {
            jedis.set(key, value);
        }
    }

    public String get(String key) {
        try (Jedis jedis = this.pool.getResource()) {
            return jedis.get(key);
        }
    }

    public void publish(String channel, String content) {
        try (Jedis jedis = this.pool.getResource()) {
            jedis.publish(channel, content);
        }
    }

    public boolean exists(String key) {
        try (Jedis jedis = this.pool.getResource()) {
            return jedis.exists(key);
        }
    }

    public void delete(String key) {
        try (Jedis jedis = this.pool.getResource()) {
            jedis.del(key);
        }
    }
}
